package com.liuliang.controller;

import com.liuliang.entity.Student;
import com.liuliang.http.AjaxResult;
import com.liuliang.service.StudentService;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 控制器
 */
@RestController //@ResponseBody+@Controller 以Json字符串的形式返回给前端
@RequestMapping("student") //将请求和处理请求的控制器方法关联起来，建立映射关系
public class StudentController {

    @Resource
    private StudentService studentService;

    //查询所有
    @GetMapping("findAll")
    public AjaxResult findAll() {
        List<Student> studentList = studentService.findAll();
        return AjaxResult.success(studentList);
    }

    //通过id查询
    @GetMapping("findById/{id}")
    public AjaxResult findById(@PathVariable("id") Integer id) {
        Student student = studentService.findById(id);
        return AjaxResult.success(student);
    }

    //新增
    @PostMapping("add")
    public AjaxResult add(@RequestBody Student student) {
        studentService.save(student);
        return AjaxResult.success();
    }

    //修改
    @PutMapping("edit")
    public AjaxResult edit(@RequestBody Student student) {
        studentService.save(student);
        return AjaxResult.success();
    }

    //删除
    @DeleteMapping("remove/{id}")
    public AjaxResult remove(@PathVariable("id") Integer id) {
        studentService.delete(id);
        return AjaxResult.success();
    }

    //批量删除
    @DeleteMapping("batchRemove/{ids}")
    public AjaxResult batchRemove(@PathVariable("ids") List<Integer> ids) {
        studentService.batchDelete(ids);
        return AjaxResult.success();
    }

    //分页条件查询
    @GetMapping("findByPage")
    public AjaxResult findByPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                 @RequestParam(defaultValue = "10") Integer pageSize,
                                 @RequestParam(defaultValue = "") String name,
                                 @RequestParam(defaultValue = "") String birthplace,
                                 @RequestParam(defaultValue = "") String major) {
        Page<Student> studentPage = studentService.findByPage(pageNum, pageSize, name, birthplace, major);
        long totalElements = studentPage.getTotalElements(); //总记录数
        return AjaxResult.success(studentPage, totalElements);
    }
}